package work.mediway.mdm.biz.listener;

import com.mediway.bpm.dal.dataobject.definition.BpmProcessDefinitionExtDO;
import com.mediway.bpm.dal.dataobject.task.BpmProcessInstanceExtDO;
import com.mediway.bpm.dal.mapper.mysql.definition.BpmProcessDefinitionExtMapper;
import com.mediway.bpm.dal.mapper.mysql.task.BpmProcessInstanceExtMapper;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.core.helper.BaseDatabaseHelper;
import work.mediway.mdm.core.vo.TableVO;
import work.mediway.mdm.biz.dto.dict.DictGeneralDTO;
import work.mediway.mdm.biz.service.common.CommonDictService;
import work.mediway.mdm.core.constant.MdmConstant;

/**
 * 表单审批监听
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2022/7/1
 */
@Slf4j
@Component("flowFormPersistenceExecutionListener")
@RequiredArgsConstructor
public class FlowFormPersistenceExecutionListener implements ExecutionListener {

    private final BpmProcessInstanceExtMapper processInstanceExtMapper;
    private final BpmProcessDefinitionExtMapper processDefinitionExtMapper;
    private final BaseDatabaseHelper baseDatabaseHelper;
    private final CommonDictService commonDictService;

    @Override
    public void notify(DelegateExecution execution) {
        BpmProcessInstanceExtDO processInstanceExt = processInstanceExtMapper.selectByProcessInstanceId(execution.getProcessInstanceId());
        // 获取表单设计信息
        BpmProcessDefinitionExtDO bpmProcessDefinitionExtDO = this.processDefinitionExtMapper.selectByProcessDefinitionId(processInstanceExt.getProcessDefinitionId());
        Map<String, Object> map = processInstanceExt.getFormVariables();
        Object tableCodeObj = map.get("tableCode");
        if (ObjectUtil.isNotEmpty(tableCodeObj)) {
            List<TableVO> databaseTable = this.baseDatabaseHelper.getTable(tableCodeObj.toString());
            if (CollUtil.isEmpty(databaseTable)) {
                log.error("表[{}]不存在", tableCodeObj);
                return;
            }
        } else {
            log.error("缺失表名信息, 跳过数据存储");
            return;
        }

        String dictGeneral = StrUtil.format(MdmConstant.DICT_GENERAL_STYLE, JSONUtil.toJsonStr(new JSONArray(CollUtil.newArrayList(map))), tableCodeObj.toString());
        DictGeneralDTO dictGeneralDTO = JSONUtil.toBean(dictGeneral, DictGeneralDTO.class);
        // 存储数据
        this.commonDictService.saveDictDetail(dictGeneralDTO, "");
    }
}
